/*
twSelectList v.1.0

- require 
-	jquery UI framework
-	jquery.autocomplete
- by tiger


data : array,
onListcomplete : callback when prased value

*/
(function($) {

    jQuery.fn.twSelectList = function(settings) {

        var defaults = {
            data: [],
            autoFill: false,
            maxItemsToShow: 10,
            sortData: false, moreData: false,
            onListcomplete: function() { return true }
        };

        var options = jQuery.extend(defaults, settings);

        var holder = $(this);
        var dataArray = options.data;

        makeToken();

        //token
        function makeToken() {

            var oldDiv = $(holder).next("div.tokenHolder");
            //add to input value
            if ($(holder).val() && $(oldDiv).find("input.twAutoTokenListKeyin").val()) {
                $(holder).val($(holder).val() + "," + $(oldDiv).find("input.twAutoTokenListKeyin").val());
            } else if ($(oldDiv).find("input.twAutoTokenListKeyin").val()) {
                $(holder).val($(oldDiv).find("input.twAutoTokenListKeyin").val());
            }
            //remove from dataArray
            $(dataArray).each(function(i) {
                if (dataArray[i] == $(oldDiv).find("input.twAutoTokenListKeyin").val()) {
                    dataArray.splice(i, 1)
                }
            });

            //create token holder
            $(holder).hide().next('div.' + $(holder).attr("id") + $(holder).attr("name")).remove();
            $(holder).after('<div class="tokenHolder ' + $(holder).attr("id") + $(holder).attr("name") + ' ui-helper-clearfix" style="clear:both; margin:0; padding:2px; height:auto!important; background-color:#FFFFFF; border:solid 1px #666666"></div>');

            var thisDiv = $(holder).next("div.tokenHolder");


            //have value
            if (holder.val()) {

                var thisArray = $(holder).val().split(",");
                //sort
                if (options.sortData) {
                    thisArray.sort();
                    $(holder).val(thisArray)
                }
                //
                thisDiv.addClass($(holder).attr("class"));

                $(thisArray).each(function(i) {
                    thisDiv.append('<span class="ui-state-active ui-corner-all" style="float:left; margin:1px; padding:1px 2px 2px 5px; white-space:nowrap; display:block"><span style="float:left; padding:2px">' + thisArray[i] + '</span><span class="ui-icon ui-icon-close removeTokenList" style="float:inherit; cursor:pointer" title="Click to remove item"></span></span>');
                });

                thisDiv.find("span").click(function(e) { e.stopPropagation(); e.cancelBubble = true; });

                thisDiv.find("span.removeTokenList").click(function(e) {
                    //
                    e.stopPropagation(); e.cancelBubble = true;
                    var removeItem = $(this).parent().text();
                    //clear input
                    $(thisDiv).find("input.twAutoTokenListKeyin").remove();
                    //remove text in val
                    var tmpArray = $(holder).val().split(",");
                    $(tmpArray).each(function(i) {
                        if (tmpArray[i] == removeItem) {
                            tmpArray.splice(i, 1);
                        }
                    });

                    var groupOfVal = tmpArray.toString();

                    //remove ","  and reindex value
                    if (groupOfVal.charAt(0) == ",") {
                        groupOfVal = groupOfVal.substr(1);
                    } else if (groupOfVal.charAt(groupOfVal.length - 1) == ",") {
                        groupOfVal = groupOfVal.substr(0, groupOfVal.length - 1);
                    }
                    if (groupOfVal.split(",,").length > 0) {
                        groupOfVal = groupOfVal.replace(",,", ",");

                    }
                    //reindex value
                    $(holder).val(groupOfVal);
                    dataArray.push(removeItem);
                    dataArray.sort();

                    makeToken();

                    $(this).parent().remove();


                });
            }

            //

            //
            if (dataArray.length || options.moreData) {
                $(thisDiv).find("input.twAutoTokenListKeyin").remove().end().append('<input type="text" class="twAutoTokenListKeyin" />');
                $(thisDiv).find("input.twAutoTokenListKeyin").keydown(function(e) {
                    var e_k = e.keyCode
                    // alert($(".ac_results ul").size())
                    if (e_k == 13 && !$(".ac_results ul").size() && options.moreData) {
                        makeToken();
                    }
                });
            }

            if (options.moreData) {
                var mathonly = false;
            } else {
                var mathonly = true;
            }
            //$("input.twAutoTokenListKeyin").focus();
            //
            if ($.autocomplete) {
                //alert(options.maxItemsToShow);
                $(thisDiv).find("input.twAutoTokenListKeyin").autocompleteArray(
					dataArray,
					{
					    focus: true,
					    delay: 10,
					    mustMath: mathonly,
					    minChars: 1,
					    selectFirst: true,
					    //selectOnly: true,
					    //cacheLength:5,
					    matchContains: true,
					    //matchSubset:2,
					    onItemSelect: makeToken,
					    //onFindValue:findValue,
					    autoFill: options.autoFill,
					    maxItemsToShow: options.maxItemsToShow
					}
				);
            } else {
                alert("require autocomplete plug-in");
            }
            //
            if (options.onListcomplete() == false) {
                return false;
            } //
            //            if ($(".ac_results").size()>1) {
            //                $(".ac_results:last").remove();
            //            }
        }
        //end token


    } //end plug-in



})(jQuery);	